package com.haoxuer.discover.quartz.web;

import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.quartz.data.entity.CronTask;
import com.haoxuer.discover.quartz.data.enums.TaskState;
import com.haoxuer.discover.quartz.data.service.CronTaskService;
import com.haoxuer.discover.quartz.task.HttpJob;
import com.haoxuer.discover.quartz.utils.SchedulerUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.ArrayList;
import java.util.List;

public class InitListener implements ServletContextListener {

    private Logger logger = LoggerFactory.getLogger("ada");

    private WebApplicationContext springContext;

    @Override
    public void contextInitialized(ServletContextEvent event) {

        Scheduler scheduler = SchedulerUtils.getScheduler();
        if (scheduler == null) {
            return;
        }
        try {
            if (!scheduler.isStarted()) {
                scheduler.start();
                logger.info("初始化定时器成功");
            }
        } catch (SchedulerException e) {
            logger.info("Scheduler启动错误", e);
        }

        springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
        if (springContext != null) {
            CronTaskService service = springContext.getBean(CronTaskService.class);
            List<Filter> filters = new ArrayList<>();
            filters.add(Filter.eq("state", TaskState.NORMAL));
            List<CronTask> tasks = service.list(0, 100, filters, null);
            if (tasks != null && tasks.size() > 0) {
                System.out.println("开启定时任务!");
                for (CronTask task : tasks) {
                    Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(task.getCron()))
                            .withIdentity("trigger" + task.getId(), "group" + task.getId()).build();
                    JobDetail jobDetail = JobBuilder.newJob(HttpJob.class)
                            .withIdentity("job" + task.getId(), "group" + task.getId()).usingJobData("url", task.getUrl())
                            .usingJobData("id", task.getId()).withDescription(task.getNote()).build();
                    try {
                        scheduler.scheduleJob(jobDetail, trigger);
                    } catch (SchedulerException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            System.out.println("获取应用程序上下文失败!");
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        Scheduler scheduler = SchedulerUtils.getScheduler();
        if (scheduler == null) {
            return;
        }
        try {
            if (scheduler.isStarted()) {
                scheduler.shutdown();
                logger.info("关闭定时器");
            }
        } catch (SchedulerException e) {
            logger.info("Scheduler关闭错误", e);
        }
    }
}
